<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>mockserv</title>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/styles/default.min.css">
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/highlight.min.js"></script>

    <script type="text/babel" src="./javascripts/ioc.js"></script>
    <script type="text/babel" src="./javascripts/itablet.jsx"></script>
    <link rel="stylesheet" type="text/css" href="stylesheets/itablet.css">

    <style>
        body{
            background-color:cornsilk;
            position: relative;
        }

        .modal {
            background-color: black;
            position: fixed;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            opacity: 0.4;
            z-index: 1000;
            display: block;
        }

        .mock-edit {
            background-color: antiquewhite;
            position: fixed;
            left: 50%;
            top: 10%;
            width: 500px;
            margin-left: -250px;
            z-index: 1001;
            padding: 15px;
        }

        .navmenu{
            position: relative;
            padding: 5px 20px;
            border-bottom: 1px solid greenyellow;
        }

        .nav-form{
            padding: 10px 20px;
            background-color: antiquewhite;
        }

        #ebutton{
            position: absolute;
            right: 20px;
            top: 26px;
        }

        .itablet{
           padding: 5px 20px;
        }

        .mock-add{

        }

        .logheader{
            padding-left: 30px;
        }

        .op-col{
            width: 300px;
        }
        .meth-col{
            width: 80px;
        }

        .nav{
            font-size: 10pt;
        }

        .table th{
            background-color:lightskyblue;
            font-size:12pt;

        }

        .readme{
            position: absolute;
            right: 20px;
            top:10px
        }

        code, pre{
            padding: 0px;
            margin: 0px;
        }
    </style>

</head>

<body>

    <div class="readme">
        <a href="/readme.html">使用说明</a>
    </div>

    <div id="app"></div>

    <script type="text/babel">

        function Cmp1(props) {
            return (<div>
                <h2>{props.name ? props.name : "no props"}</h2>
            </div>)
        }

        class Navmenu extends IOC.Component {

            constructor(props) {
                super(props)
                this.state = {
                    select: undefined,
                    toggle:false,
                }

            }

            componentDidMount() {

                $.get({
                    url: '/collections',
                    success: (data) => {
                        this.setState({
                            collections: data,
                        })
                    }
                })
            }

            navclick(item) {
                // console.log(item)
                // console.log("current ", this.state.current)
                this.setState({
                    select: item.name,
                    current: item,
                })

                let elem = <Resmocks coll={item.name} collpath={item.path}/>
                IOC.getBean('itablet').append({
                    type:'el',
                    tablabel:item.name,
                    element:elem,
                    key:item.name
                })
            }

            editclick(){
                this.setState({
                    toggle: !this.state.toggle
                })
            }

            renderForm() {
             //   return <CollectForm name={this.state.current.name} path={this.state.current.path} descrip={this.state.current.descrip} />
              
              let props = this.state.current ? this.state.current : {id:"000",name:'example', path:"your_path", descrip:"your_description"}

             
              return <CollectForm {...props} />
            }

            render() {

                return (
                    <div className="navmenu">
                        <ul className="nav nav-pills">
                            {
                                this.state.collections && this.state.collections.map((item, index) => {
                                    return (<li key={item.name} className={this.state.select == item.name ? 'active' : ''} >
                                        <a onClick={() => { this.navclick(item) }}>{item.name}</a>
                                    </li>)
                                })
                            }
                        </ul>
                        <div id="ebutton"><button className="btn btn-success btn-xs" onClick={()=>{this.editclick()}}>
                            <span className="glyphicon glyphicon-pencil" ></span> &nbsp;
                            EDIT &nbsp;</button></div>
                        {this.state.toggle && this.renderForm()}
                    </div>
                )
            }
        }




        const CollectForm = (props) => {
            // props.name, path, description

            const onclick = (e) => {
                e.preventDefault()
                var d = {}
                var t = $('#coll-form').serializeArray();
                $.each(t, function () {
                    d[this.name] = this.value;
                });
                // console.log(d)
                $.ajax({
                    type: 'PUT',
                    url: "/collections",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(d),
                    success: function (resp) {

                        alert(JSON.stringify(resp))
                        IOC.getBean('navmenu').componentDidMount()

                    },
                    error: function () {
                        alert("ERROR , OPERATION FAILED!!!")
                    }
                })
            }

            const ondelete=(e)=>{
                e.preventDefault()

                var r = confirm("确认删除吗")
                if(r==false){
                    return;
                }

                var d = {}
                var t = $('#coll-form').serializeArray();
                $.each(t, function () {
                    d[this.name] = this.value;
                });
                // console.log(d)
                $.ajax({
                    type: 'DELETE',
                    url: "/collections/"+d.id,
                    success: function (resp) {
                        IOC.getBean('navmenu').componentDidMount()
                        IOC.getBean('navmenu').editclick()
                    },
                    error: function () {
                        alert("ERROR , OPERATION FAILED!!!")
                    }
                })
            }
            const html1 = `<label>name:</label><input class="form-control" type="text" name="name" value=` + props.name + `></input>`
            const html2 = `<label>path:</label><input class="form-control" type="text" name="path" value=` + props.path + `></input>`
            const html3 = `<label>description:</label><input class="form-control" type="text" name="descrip" value=` + props.descrip + `></input>`
            return (<div className="nav-form">
                <form id="coll-form" className="form-inline">
                    <input type="hidden" name='id' value={props.id}/>
                    <div className="form-group" dangerouslySetInnerHTML={{ __html: html1 }}>
                    </div>

                    <div className="form-group"  dangerouslySetInnerHTML={{ __html: html2 }}>
                    </div>

                    <div className="form-group"  dangerouslySetInnerHTML={{ __html: html3 }}>
                    </div>
                    <div className="form-group">
                        <button className='btn btn-sm btn-primary' type="submit" onClick={onclick}>NEW / UPDATE</button>
                        &nbsp;
                        <button className='btn btn-sm btn-danger' type="submit" onClick={ondelete}>删除</button>
                    </div>
                </form>
            </div>)
        }

        class CollectionEdit extends IOC.Component {

            constructor(props) {
                super(props)
                this.state = {
                    name: null,
                    path: null,
                    descrip: null,
                    eflag: false
                }
            }

            render() {
                return (<div>
                    <form>
                        <label>name:</label>
                        <input type="text" name="name" />
                        <label>path:</label>
                        <input type="text" name="path" />
                        <label>description:</label>
                        <input type="text" name="descrip" />
                    </form>
                </div>)
            }
        }


        class Resmocks extends IOC.Component {
            constructor(props) {
                super(props)
                this.state = {
                    mocks: [],
                    collection: null,
                    mockitem: null,
                    editflag: false,
                }
            }

            componentDidMount() {
                let coll = this.props.coll;
                $.get({
                    url: "/resmocks/" + coll,
                    success: (data) => {
                        // console.log("resmocks", data)
                        this.setState({
                            collection: coll,
                            mocks: data
                        })
                    },
                    error: (err) => {
                        console.error("get resmocks error")
                    }
                })
            }

            componentDidUpdate(){
                hljs.initHighlighting();
            }

            itemEditClick(mitem) {
                this.setState({
                    mockitem: mitem,
                    editflag: true,
                })
            }

            itemTestClick(mitem){
                let nurl = "/m/" + this.props.collpath + mitem.url;
                let method = mitem.meth
                if(method=='ALL')
                    method='GET'
                
                $.ajax({
                    url:nurl,
                    type:method,
                    success:(data, textstatu)=>{
                        console.info("Mock Success:", nurl)
                        console.log("Receive:", data)
                        console.log("response status:", textstatu)
                    },
                    error:(jxhr, textstatus, err)=>{
                        console.warn("Mock Test Request Error:",nurl)
                        console.warn("ResponsText:", jxhr.responseText)
                    }
                })
            }

            itemRemoveClick(mitem){
                let mid = mitem.id
                let r = confirm("确认删除吗? " + mitem.name)
                if(r==false){
                    return ;
                }

                $.ajax({
                    url:"/resmocks/"+mid,
                    type:'DELETE',
                    success:(data)=>{
                        // console.log("delete return:"+data)
                        this.componentDidMount()
                    },
                    error:(jxhr, statu)=>{
                        console.error("delete resmocks error:", statu, jxhr.responseText)
                    }
                })
            }
            itemAddNewClick(){
                this.setState({
                    editflag:true,
                    mockitem:null,
                })
            }

            formCancelClick(e) {
                e.preventDefault()
                this.setState({
                    mockitem: null,
                    editflag: false
                })
            }

            formSumbitClick(e) {

                e.preventDefault()
                var d = {}
                var t = $('#form-mock-edit').serializeArray();
                $.each(t, function () {
                    d[this.name] = this.value;
                });
                // console.log(d)
                $.ajax({
                    type: 'PUT',
                    url: "/resmocks",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(d),
                    success: (resp) => {
                        // alert(JSON.stringify(resp))
                        this.componentDidMount()
                        this.setState({
                            editflag: false
                        })
                    },
                    error: function () {
                        alert("ERROR , OPERATION FAILED!!!")
                        this.setState({
                            editflag: false
                        })
                    }
                })
            }

            render() {

                return (
                    <div className="mocks-list">
                        <div className="text-center">
                            <button className="btn btn-sm btn-success" onClick={this.itemAddNewClick.bind(this)}>
                            <span className="glyphicon glyphicon-pencil" ></span>
                            &nbsp; Add New Api &nbsp;</button>
                        </div>
                        <table className="table table-bordered table-condensed" >
                            <thead>
                                <tr>
                                    <th className="na-col">name</th>
                                    <th className="url-col">url</th>
                                    <th className="meth-col">method</th>
                                    <th className="desc-col">description</th>
                                    <th className="code-col">code</th>
                                    <th className="op-col">op</th>
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    this.state.mocks && this.state.mocks.map((item, idx) => {

                                        return (<tr key={item.name + idx}>

                                            <td>{item.name}</td>
                                            <td>{item.url}</td>
                                            <td>{item.meth}</td>
                                            <td><pre><code>{item.descrip}</code></pre></td>
                                            <td><pre><code className="lang-javascript">{item.fcode}</code></pre></td>
                                            <td>
                                                <button className="btn btn-default" onClick={() => { this.itemEditClick(item) }}>
                                                  
                                                    <span className="glyphicon glyphicon-pencil" ></span> 
                                                    &nbsp; Edit
                                                    </button>

                                                <button className="btn btn-success" onClick={() => { this.itemTestClick(item) }}>
                                                    <span className="glyphicon glyphicon-zoom-in" ></span> 
                                                    &nbsp;
                                                    Testing&nbsp;&nbsp;&nbsp;
                                                </button>

                                                <button className="btn btn-danger" onClick={() => { this.itemRemoveClick(item) }}>
                                                    <span className="glyphicon glyphicon-remove" ></span> 
                                                    &nbsp;
                                                    Delete
                                                </button>
                                            </td>
                                        </tr>)
                                    })
                                }
                            </tbody>
                        </table>

                        {
                            this.state.editflag && <div>
                                <div className="modal">1</div>
                                <div className="mock-edit">
                                    <form className="form-horizontal" id="form-mock-edit">
                                        <input type='hidden' name="id" defaultValue={this.state.mockitem ? this.state.mockitem.id : ""} />
                                        <input type='hidden' name="collect" defaultValue={this.props.coll ? this.props.coll : ""} />

                                        <div className="form-group">
                                            <label className="col-sm-2 text-right">name:</label>
                                            <div className="col-sm-10">
                                                <input type='text' className="form-control" name="name" defaultValue={this.state.mockitem ? this.state.mockitem.name : ""} />
                                            </div>
                                        </div>

                                        <div className="form-group">
                                            <label className="col-sm-2 text-right">url:</label>
                                            <div className="col-sm-10">
                                                <input type='text' className="form-control" name="url" defaultValue={this.state.mockitem ? this.state.mockitem.url : ""} />
                                            </div>
                                        </div>

                                   

                                        <div className="form-group">
                                            <label className="col-sm-2 text-right">method:</label>
                                            <div className="col-sm-10">
                                                <select className="form-control" name="meth" defaultValue={this.state.mockitem ? this.state.mockitem.meth : ""}>
                                                    <option value='GET'>GET</option>
                                                    <option value='POST'>POST</option>
                                                    <option value='PUT'>PUT</option>
                                                    <option value='DELETE'>DELETE</option>
                                                    <option value='ALL'>ALL</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div className="form-group">
                                            <label className="col-sm-2 text-right">description:</label>
                                            <div className="col-sm-10">
                                                {/*
                                                       <input type='text' className="form-control" name="descrip" defaultValue={this.state.mockitem ? this.state.mockitem.descrip : ""} />
                                                */}

                                                <textarea className="form-control" rows="5" name="descrip" defaultValue={this.state.mockitem ? this.state.mockitem.descrip : ""}></textarea>
                                              
                                            </div>
                                        </div>

                                        <div className="form-group">
                                            <label className="col-sm-2 text-right">fcode:</label>
                                            <div className="col-sm-10">
                                                <textarea className="form-control" rows="10" name="fcode" defaultValue={this.state.mockitem ? this.state.mockitem.fcode : ""}></textarea>
                                            </div>
                                        </div>
                                        <div className="form-group">
                                            <div className="col-sm-offset-2 col-sm-10">
                                                <button className="btn btn-primary" onClick={this.formSumbitClick.bind(this)}>提交</button>
                                                <button className="btn btn-default" onClick={this.formCancelClick.bind(this)}>取消</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        }




                    </div>)
            }
        }


        class AppMain extends IOC.Component{

            render(){

                return (<div>
                    
                    <div className="logheader h4 text-center">
                        Api Mock Server
                    </div>

                    <Navmenu id='navmenu'/>
                    <ITablet id='itablet' />
                    
                    </div>)
            }
        }


        ReactDOM.render(
            <AppMain />
            , document.getElementById("app")
        )




        let col = { name: 'project1', path: "path", descrip: "project11111" }



    </script>

</body>

</html>